/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package controllers;

import java.util.Date;
import java.util.List;
import models.Employee;
import models.Group;
import models.User;
import play.data.validation.Valid;
import play.i18n.Messages;
import play.mvc.*;

/**
 *
 * @author GJean
 */
@With(Secure.class)
public class Employees extends Controller {

    public static User user;

    @Before
    static void setConnectedUser() {
        if (Security.isConnected()) {
            user = User.find("byUsername", Security.connected()).first();
            renderArgs.put("user", user);


        }
    }

    public static void list() {
        List<Employee> entities = Employee.all().fetch();
        render(entities);
    }

    public static void show(Long id) {
        Employee entity = Employee.findById(id);

        render(entity);

    }

    public static void create(Long id) {

        User entityUser = User.findById(id);

        render(entityUser);

    }

    public static void edit(Long id) {
        Employee entity = Employee.findById(id);
        User entityUser = User.findById(entity.user.id);
        render(entity, entityUser);
    }

    public static void delete(Long id) {
        Employee entity = Employee.findById(id);
        User entityUser = User.findById(entity.user.id);
        Group group = Group.findById((long) 4);
        entityUser.groups = group;
        entity.delete();
        entityUser.merge();
        entityUser.save();

        flash.success(Messages.get("Users.deleted"));
        Customers.list();

    }

    public static void save(@Valid Employee entity) {
        entity.hiredate = new Date();
        entity.firedate = null;
        entity.hours = (double) 0;
        entity.salary = (double) 0;
        User entityUser = User.findById(entity.user.id);
        Group group = Group.findById((long) 2);
        entityUser.groups = group;
        entity.delete();
        entityUser.merge();
        entityUser.save();


        if (validation.hasErrors()) {
            flash.error(Messages.get("validation"));

            render("@create", entity);
        }
        entityUser = entityUser.merge();
        entity.save();
        entityUser.save();
        flash.success(Messages.get("Customers.created"));
        Admin.index();
    }

    public static void update(@Valid Employee entity) {
        if (validation.hasErrors()) {
            flash.error(Messages.get("validation"));

            render("@create", entity);
        }
        entity.merge();
        entity.save();
        Employees.list();


    }
}
